package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRoute;
import com.ruoyi.common.core.domain.entity.SysRouteAxes;
import com.ruoyi.common.pojo.AddRouteAxesReq;
import com.ruoyi.common.pojo.AddRouteInfoReq;
import com.ruoyi.common.pojo.DeleteRouteInfoReq;
import com.ruoyi.common.pojo.QueryRouteListReq;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.ImageUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.system.mapper.SysRouteAxesMapper;
import com.ruoyi.system.mapper.SysRouteMapper;
import com.ruoyi.system.service.SysRouteService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author
 * @description 针对表【sys_route(路径信息表)】的数据库操作Service实现
 * @createDate 2022-07-16 18:29:36
 */
@Slf4j
@Service
public class SysRouteServiceImpl implements SysRouteService {

    @Autowired
    SysRouteMapper sysRouteMapper;

    @Autowired
    SysRouteAxesMapper sysRouteAxesMapper;

    @Value("${url}")
    private String url;

    @Value("${key}")
    private String value;

    @Override
    public AjaxResult queryRouteList(QueryRouteListReq param) {
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        List<SysRoute> sysRouteAxes = sysRouteMapper.selectList(Wrappers.<SysRoute>lambdaQuery()
                .eq(SysRoute::getState, 1)
                .eq(Objects.nonNull(param.getId()),SysRoute::getId,param.getId())
                .ge(StringUtils.isNotBlank(param.getStartTime()), SysRoute::getCreateTime, DateUtils.parseDate(param.getStartTime()))
                .le(StringUtils.isNotBlank(param.getEndTime()), SysRoute::getCreateTime, DateUtils.parseDate(param.getEndTime()))
                .like(StringUtils.isNotBlank(param.getName()),SysRoute::getPathName,param.getName())
                .orderByDesc(SysRoute::getCreateTime));
        sysRouteAxes.forEach(v -> {
            List<SysRouteAxes> sysRouteAxesList = sysRouteAxesMapper.selectList(Wrappers.<SysRouteAxes>lambdaQuery().eq(SysRouteAxes::getRoute, v.getId()));
            v.setRouteAxesList(sysRouteAxesList);
        });
        PageInfo<SysRoute> pageInfo = new PageInfo<SysRoute>(sysRouteAxes);
        return AjaxResult.success(pageInfo);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class}, propagation = Propagation.REQUIRES_NEW)
    public AjaxResult addRouteInfo(AddRouteInfoReq param) {

        log.info("添加路径请求参数:{}",param);
        String uri = url + "key=" + value + "&zoom=" + param.getZoom() + "&size=" + param.getSize() + "&paths=" + param.getPaths();
        log.info("生成高德静态图片url:{}",uri);

        byte[] data = ImageUtils.readFile(uri);

        String img = null;

        try {
            MultipartFile file = new MockMultipartFile("file", "response.png", "image/png;charset=UTF-8", data);
            img = FileUploadUtils.upload(RuoYiConfig.getPlanPath(),file, MimeTypeUtils.IMAGE_EXTENSION);
        } catch (Exception e) {
            log.error("获取静态地图图片异常", e);
            return AjaxResult.error("保存静态地图失败");
        }

        Date nowDate = DateUtils.getNowDate();
        SysRoute sysRoute = SysRoute.builder()
            .pathName(param.getPathName())
            .remark(param.getRemark())
            .type(param.getType())
            .createTime(nowDate)
            .number(0)
            .img(img)
            .state(1)
            .build();
        sysRouteMapper.insert(sysRoute);

        List<AddRouteAxesReq> axes = param.getAxes();
        axes.forEach(
            v -> {
                SysRouteAxes sysRouteAxes = SysRouteAxes.builder()
                    .route(sysRoute.getId())
                    .latitude(v.getLatitude())
                    .longitude(v.getLongitude())
                    .createTime(nowDate)
                    .sort(v.getSort())
                    .state(1)
                    .build();
                sysRouteAxesMapper.insert(sysRouteAxes);
            });
        return AjaxResult.success();
    }

    @Override
    public AjaxResult deleteRouteInfo(DeleteRouteInfoReq param) {
        SysRoute sysRoute = SysRoute.builder().state(0).id(param.getId()).build();
        sysRouteMapper.updateById(sysRoute);
        return AjaxResult.success();
    }
}




